package cn.b.sky.schedule.job;

import cn.b.sky.common.utils.SpringBeanUtil;
import cn.b.sky.schedule.model.TimedJobInfo;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;

import java.text.ParseException;

/**
 * 
 * <strong>Title : TimeJobUtils.java<br></strong>
 * <strong>Package : cn.b.sky.schedule.job<br></strong>
 * <strong>Description : </strong>定时任务工具类<br> 
 * <strong>Create on : 2016-6-21 下午4:03:27<br></strong>
 * <p>
 * @author lidapeng<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人|修改日期|修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
public class TimeJobUtils {


  private TimeJobUtils() {
    // Auto-generated constructor stub
  }

  public static JobDetail getJobDetail(TimedJobInfo job) throws ClassNotFoundException, NoSuchMethodException {

    QuartzJobInvocationHandler handler = new QuartzJobInvocationHandler();
    /**
     * 调整对象获取方式，从Spring容器取对象，若不存在对象，则动态注册对象Bean，且动态注册对象Bean采用非单例模式
     */
    if (!SpringBeanUtil.containsBean(job.getJobClass())) {
      SpringBeanUtil.registerBeanDefinition(job.getJobClass(), Class.forName(job.getJobClass()), null, null, false);
    }

    handler.setTargetObject(SpringBeanUtil.getBean(job.getJobClass()));
    handler.setTargetMethod("executeManual");
    handler.setConcurrent(job.getConcurrent() == 0 ? true : false);
    handler.setArguments(new Object[] { job });
    handler.setName(job.getJobCode());
    handler.prepare();
    return handler.getJobDetail();
  }

  public static CronTriggerFactoryBean getTriggerBean(TimedJobInfo job) throws ParseException {
    CronTriggerFactoryBean cornTrigger = new CronTriggerFactoryBean();
    cornTrigger.setName(job.getJobCode());
    cornTrigger.setGroup(Scheduler.DEFAULT_GROUP);
    // 设置JobDetail，定时表达式
    cornTrigger.setCronExpression(job.getCronExpression());
    return cornTrigger;
  }
}
